package com.jiahe.video.task;

import cn.hutool.core.date.DateUtil;
import com.jiahe.video.config.AppConfig;
import com.jiahe.video.service.impl.AbsCommonService;
import com.jiahe.video.util.AppUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class Task extends AbsCommonService {

    @Resource
    private AppConfig appConfig;

    @Scheduled(cron = "0/30 * * * * ?")
    public void deleteFile() {
        // 半小时
        final long before = 3600 * 1 / 2;
        List<File> allFiles = AppUtil.getAllFiles(appConfig.getFilePathRoot());
        if (allFiles.size() < 100) {
            return;
        }
        for (File file : allFiles) {
            String fileNameWithoutExtension = file.getName().replaceFirst("[.][^.]+$", "");
            if (fileNameWithoutExtension.matches("\\d{14}")) {
                Date date = DateUtil.parse(fileNameWithoutExtension, "yyyyMMddHHmmss");
                if ((System.currentTimeMillis() - date.getTime()) / 1000 > before) {
                    log.info("删除文件：{}", file.getAbsolutePath());
                    file.delete();
                }
            }
        }

    }

}
